package zhupf.test.proxyTest.cglibProxyTest;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyObject implements MethodInterceptor {
    // 被增强的业务对象
    private Object targer;

    // 获取代理对象，即绑定业务对象
    public Object getInstance(Object targer){
        this.targer = targer;
        //创建加强器,用来创建动态代理类
        Enhancer enhancer = new Enhancer();
        //为加强器指定要代理的业务类(即:为下面生成的代理类指定父类)
        enhancer.setSuperclass(targer.getClass());
        //设置回调:对于代理类上所有方法的调用,都会调用CallBack,而CallBack则需要实现intercept()方法进行拦截
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib 前置加强处理");
        Object o1 = methodProxy.invokeSuper(o, objects);
        System.out.println("cglib 后置加强处理");
        return o1;
    }
}
